<template>
	<view class="editInfo">
		<view class="form-item">
			<view class="label">
				<text>头像</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue" @tap="chooseImg">
				<image :src="form.avatar" mode=""></image>
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>昵称</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue">
				<input v-model="form.nickname" type="text" placeholder="请输入">
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>姓名</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue">
				<input v-model="form.realName" type="text" placeholder="请输入">
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>手机号</text>
				<text class="require">*</text>
			</view>
			<view class="vlaue">
				<input v-model="form.phoneNumber" type="text" placeholder="请输入" :disabled="true">
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>职务</text>
			</view>
			<view class="vlaue">
				<input v-model="form.jobTitle" type="text" placeholder="0~15字">
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>微信号</text>
			</view>
			<view class="vlaue">
				<input v-model="form.wechatId" type="text" placeholder="请输入">
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>企业电话</text>
			</view>
			<view class="vlaue">
				<input v-model="form.companyPhone" type="text" placeholder="请输入">
			</view>
		</view>
		<view class="form-item">
			<view class="label">
				<text>所属部门</text>
			</view>
			<view class="vlaue">
				<input v-model="form.department" type="text" placeholder="0~15字">
			</view>
		</view>
		<view class="btn" @tap="submit">保存</view>
		<poster ref="poster" :list="list" background-color="#FFF" :width="563" :height="450"
		            @on-success="posterSuccess" @on-error="posterError"></poster>
		<canvas canvas-id="imgCanvas" class="imgCanvas" />
	</view>
</template>

<script>
import http from '@/utils/http.js'
import { imgCompress } from '@/utils/index.js'
import Poster from '../../components/zhangyuhao-poster/Poster.vue'
export default {
	components: {
		Poster
	},
	data() {
		return {
			form: {
			  "avatar": "",
			  "nickname": "",
			  "realName": "",
			  "phoneNumber": "",
			  "jobTitle": "",
			  "wechatId": "",
			  "companyPhone": "",
			  "department": ""
			},
			info: {},
			list: []
			// form: {"createTime":1746781878000,"updateTime":1746781878000,"creator":"3","updater":"3","deleted":false,"id":3,"openId":null,"avatar":null,"nickname":"你好","realName":"李皓","phoneNumber":"15526468743","jobTitle":"总裁","wechatId":"vvv","companyPhone":"13685236985","department":"财务部"}
		}
	},
	onLoad() {
		this.getData()
	},
	methods: {
		upload(filePath) {
			// infra/file/upload?path=yudaoyuanma.png
			// http({
			// 	url: `infra/file/upload?path=yudaoyuanma.png`,
			// 	method: 'put',
			// 	data: {
			// 		...this.form
			// 	}
			// })
			const fileName = filePath.split('/').pop()
			uni.uploadFile({
			  url: `https://ywtmp.hnwytkj.com/app-api/infra/file/upload?path=${fileName}`, //仅为示例，非真实的接口地址
			  filePath,
			  name: 'file',
			  // formData: {},
			  success: (uploadFileRes) => {
				const res = JSON.parse(uploadFileRes.data)
				console.log(uploadFileRes.data);
				if (res.code === 0) {
					this.form.avatar = res.data
				}
			  },
			  fail: (res) => {
				  console.log(res)
			  }
			});
		},
		chooseImg() {
			uni.chooseImage({
			    count: 1, //默认9
			    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			    sourceType: ['album'], //从相册选择
				success: (res) => {
					console.log(res.tempFilePaths)
					this.upload(res.tempFilePaths[0])
					// for (let i = 0; i < res.tempFilePaths.length; i++) {
					// 	const item = res.tempFilePaths[i]							
					// 	const ossPath = await this.upload(item)
					// 	this.imgList.push(ossPath)
					// 	console.log(this.imgList)
					// }
				}
			});				
		},
		editCard() {
			uni.navigateTo({
				url: '/pagesA/edit/editCard'
			})
		},
		async posterSuccess(url) {
			console.log(url)	
			// const initPath = await imgCompress.getCompressImage(url, 0.2)
			// debugger
			// uni.uploadFile({
			//   url: `https://ywtmp.hnwytkj.com/app-api/infra/file/upload?path=images/${this.info.companyProfileDO.id}/shareCard.jpg`,
			//   filePath: initPath,
			//   name: 'file',
			//   success: (uploadFileRes) => {
			// 	uni.hideLoading()
			// 	uni.showToast({
			// 		title: '保存成功',
			// 		icon: "success"
			// 	});
			//   },
			//   fail: (res) => {
			// 	  console.log(res)
			//   }
			// });	
			uni.compressImage({
				src: url, // 原图片的路径
				quality: 80, // 压缩质量，这里设置为80
				compressedWidth: 500,
				success: res => {
					console.log("成功", res.tempFilePath);
					uni.uploadFile({
					  url: `https://ywtmp.hnwytkj.com/app-api/infra/file/upload?path=images/${this.info.companyProfileDO.id}/shareCard.jpg`,
					  filePath: res.tempFilePath,
					  name: 'file',
					  success: (uploadFileRes) => {
						uni.hideLoading()
						uni.showToast({
							title: '保存成功',
							icon: "success"
						});
						this.saveInfo()
					  },
					  fail: (res) => {
						  console.log(res)
					  }
					});
				},
				fail: (error) => {
					console.log("失败");
				},
			});
		},
		posterError(err) {
			uni.hideLoading()
		},
		createdPoster() {
			this.list = [{
					type: 'image',
					path: 'https://ywtmp.hnwytkj.com/static/images/shareCardBj.jpg',//this.info.userProfileDO.avatar,
					x: 0,
					y: 0,
					width: 563,
					height: 450
				},
				{
					type: 'text',
					text: this.form.realName || '',
					x: 85,
					y: 85,
					size: 24,
					color: '#493b25'
				},
				{
					type: 'text',
					text: this.info.companyProfileDO.companyName || '',
					x: 85,
					y: 120,
					size: 16,
					color: '#766f5c'
				},
				{
					type: 'image',
					path: this.form.avatar || '',
					x: 356,
					y: 71,
					shape: 'circle',
					width: 110,
					height: 110
				},
				{
					type: 'text',
					text: this.form.phoneNumber,
					x: 110,
					y: 210,
					size: 16,
					color: '#766f5c'
				},
				{
					type: 'textarea',
					text: this.info.companyProfileDO.address ? this.info.companyProfileDO.address.address : '',
					x: 110,
					y: 260,
					width: 395,
					height: 160,
					size: 16,
					color: '#766f5c'
				}
			];
			return new Promise((resolve, reject) => {
				// 生成图片
				this.$nextTick(() => {
					// 要放在$nextTick()里，不然会空白
					this.$refs.poster.create();	
					resolve()
				})
			})
		},
		submit() {			
			if (!this.form.avatar) {
				uni.showToast({
					title: '请上传头像',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.nickname) {
				uni.showToast({
					title: '请填写昵称',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.realName) {
				uni.showToast({
					title: '请填写姓名',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.phoneNumber) {
				uni.showToast({
					title: '请填写手机号',
					icon: 'none'
				});
				return false;
			}
			// if (!this.form.jobTitle) {
			// 	uni.showToast({
			// 		title: '请填写职务',
			// 		icon: 'none'
			// 	});
			// 	return false;
			// }
			// if (!this.form.wechatId) {
			// 	uni.showToast({
			// 		title: '请填写微信号'
			// 	});
			// 	return false;
			// }
			// if (!this.form.companyPhone) {
			// 	uni.showToast({
			// 		title: '请填写企业电话'
			// 	});
			// 	return false;
			// }
			// if (!this.form.department) {
			// 	uni.showToast({
			// 		title: '请填写所属部门'
			// 	});
			// 	return false;
			// }
			uni.showLoading({
				title: '保存中...',
				mask: true
			})
			http({
				url: 'card/user-profile/personal/update',
				method: 'put',
				data: {
					...this.form
				}
			}).then(res => {				
				if(res.code === 0) {					
					if ((this.info.userProfileDO.avatar !== this.form.avatar) || 
						(this.info.userProfileDO.realName !== this.form.realName) || 
						(this.info.userProfileDO.phoneNumber !== this.form.phoneNumber)						
					) {
						this.createdPoster()
					} else {
						// this.saveInfo()
						uni.showToast({
							title: '保存成功',
							icon: "success"
						});						
					}			
				}
			})
		},
		saveInfo() {
			const business_id = getApp().globalData.business_id
			const safeEncoded = '0'
			if (!business_id) {
				return false
			}
			uni.login({
				provider: 'weixin', //使用微信登录
				success: (res) => {					
					uni.request({
						url: `https://newretail.3d89178.com.cn/api/Tp_User/addCardInfo?business_id=${business_id}&phone=${safeEncoded}&jscode=${res.code}&login_name=${this.form.phoneNumber}`,
						method: 'GET',
						success(response) {
							console.log(response)
							const {
								statusCode,
								data,
								errMsg
							} = response;
							if (statusCode === 200) {
								if (data.code === 0) {
									if (!this.info.userProfileDO.realName) {
										uni.navigateToMiniProgram({
										  appId: 'wx534aae667bce24a9',
										  path: `pages/index/index?business_id=${business_id}`,
										})
									}									
								}
							}							
						}
					})
				}
			})
		},
		getData() {
			http({
				url: 'card/user-profile/get'
			}).then(res => {				
				if(res.code === 0) {
					const data = res.data
					if (data.companyProfileDO.address) {
						try {
							data.companyProfileDO.address = JSON.parse(data.companyProfileDO.address)
						} catch (error) {
							//TODO handle the exception
							data.companyProfileDO.address = {}
						}
					}
					this.info = JSON.parse(JSON.stringify(data))
					this.form = res.data.userProfileDO
				}
			})		
		}
	},
}
</script>

<style lang="scss" scoped>
	.editInfo {
		background: #F0F0F4;
		min-height: 100vh;
		padding: 20rpx 20rpx calc(20rpx + var(--safe-area-inset-bottom));
		box-sizing: border-box;
		font-family: PingFang SC;
		.form-item {
			background: #FFFFFF;
			border-radius: 40rpx;
			padding: 38rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
			margin-bottom: 20rpx;
			.label {
				display: flex;
				align-items: center;
				margin-right: 30rpx;
				.require {
					font-weight: bold;
					color: #FF6060;
				}
			}
			.vlaue {
				flex: 1;
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
				text-align: right;
				image {
					width: 130rpx;
					height: 130rpx;
					// background: #ECECEC;
					border-radius: 20rpx;
				}
				input {
					width: 100%;
					text-align: right;
				}
				.select {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					.placeholder {
						color: #666;
					}
				}
			}
			.section {
				flex: 1;
				.title {
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 25rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.text-btn {
						font-weight: 500;
						font-size: 28rpx;
						color: #4B73FF;
					}
					.require {
						font-weight: bold;
						color: #FF6060;
					}
				}
				textarea {
					font-weight: 500;
					font-size: 28rpx;
					// color: #CCCCCC;
					color: #333333;
					border-radius: 10rpx;
					border: 1rpx solid #EEEEEE;
					width: 100%;
					height: 130rpx;
					box-sizing: border-box;
					padding: 28rpx 24rpx;
					&::placeholder {
						color: #CCCCCC;
					}
				}
			}
		}
		.btn {
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
			background: #4B73FF;
			border-radius: 20rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #FFFFFF;
			margin-top: 42rpx;
		}
	}
	.imgCanvas{
		position: absolute;
		top: -100%;
		width: 100%;
		height: 100%;
	}
</style>